package org.ns.framework.datasource.mybatis;

import java.util.function.Consumer;
import java.util.function.Function;

import org.ns.framework.datasource.database.SegmentMode;
import org.ns.framework.datasource.database.TransactionSegment;

public class MybatisTransactionSegment implements TransactionSegment<TransactionManage> {
	private MybatisTransactionReference reference;

	public MybatisTransactionSegment() {

	}

	public MybatisTransactionSegment(MybatisTransactionReference reference) {
		this.reference = reference;
	}

	public CommitResult commit(Function<TransactionManage, ?> exe) {
		try (TransactionManage tx = TransactionManage.create()) {
			Object result = exe.apply(tx);
			CommitResult commitResult = tx.commit();
			commitResult.setResult(result);
			return commitResult;
		}
	}

	public CommitResult commit(Consumer<TransactionManage> exe) {
		return commit((tx) -> {
			exe.accept(tx);
			return null;
		});
	}

	public void cancel() {
		if (reference != null) {
			reference.unsegment(SegmentMode.tempSegment);
		}
	}
}
